{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 数据连接",
   "id": "6f17bb50a9c8f014"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-14T05:35:52.559574Z",
     "start_time": "2025-01-14T05:35:52.544993Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "df_obj1 = pd.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],\n",
    "                        'data1' : np.random.randint(0,10,7)})\n",
    "df_obj2 = pd.DataFrame({'key': ['a', 'b' ,'d'],\n",
    "                        'data2' : np.random.randint(0,10,3)})\n",
    "\n",
    "print(df_obj1)\n",
    "print('-'*50)\n",
    "print(df_obj2)\n",
    "\n",
    "#默认连接使用相同的列名，连接方式是内连接，即只保留两个DataFrame中都存在的列\n",
    "print(pd.merge(df_obj1, df_obj2))\n",
    "\n",
    "#左df和右df都拿索引连接\n",
    "print(pd.merge(df_obj1, df_obj2,left_index=True,right_index=True)) # 只取前几行，直到其中一个取完\n",
    "\n",
    "#左表和右表都拿key列来连接\n",
    "pd.merge(df_obj1, df_obj2, on='key')\n",
    "\n"
   ],
   "id": "bbcf368e573986b4",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  key  data1\n",
      "0   b      1\n",
      "1   b      5\n",
      "2   a      0\n",
      "3   c      6\n",
      "4   a      2\n",
      "5   a      6\n",
      "6   b      2\n",
      "--------------------------------------------------\n",
      "  key  data2\n",
      "0   a      9\n",
      "1   b      7\n",
      "2   d      5\n",
      "  key  data1  data2\n",
      "0   b      1      7\n",
      "1   b      5      7\n",
      "2   a      0      9\n",
      "3   a      2      9\n",
      "4   a      6      9\n",
      "5   b      2      7\n",
      "  key_x  data1 key_y  data2\n",
      "0     b      1     a      9\n",
      "1     b      5     b      7\n",
      "2     a      0     d      5\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "  key  data1  data2\n",
       "0   b      1      7\n",
       "1   b      5      7\n",
       "2   a      0      9\n",
       "3   a      2      9\n",
       "4   a      6      9\n",
       "5   b      2      7"
      ],
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>key</th>\n",
       "      <th>data1</th>\n",
       "      <th>data2</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>b</td>\n",
       "      <td>1</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>b</td>\n",
       "      <td>5</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>a</td>\n",
       "      <td>0</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>a</td>\n",
       "      <td>2</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>a</td>\n",
       "      <td>6</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>b</td>\n",
       "      <td>2</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-14T05:38:28.039918Z",
     "start_time": "2025-01-14T05:38:28.026098Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 更改列名\n",
    "df_obj1 = df_obj1.rename(columns={'key':'key1'})\n",
    "df_obj2 = df_obj2.rename(columns={'key':'key2'})\n",
    "\n",
    "#左表以key1来连接，右表以key2来连接\n",
    "print(pd.merge(df_obj1, df_obj2, left_on='key1', right_on='key2'))\n",
    "\n",
    "#全外连接\n",
    "print(pd.merge(df_obj1, df_obj2, left_on='key1', right_on='key2', how='outer'))  #全外连接, 即保留左右表中都存在的列, 并用NaN填充缺失值\n",
    "\n",
    "print(pd.merge(df_obj1, df_obj2, left_on='key1', right_on='key2', how='left'))  #左外连接, 即保留左表中存在的列(即左边行索引不变), 右表中不存在的列用NaN填充\n",
    "\n",
    "print(pd.merge(df_obj1, df_obj2, left_on='key1', right_on='key2', how='right'))  #右外连接, 即保留右表中存在的列(即右边行索引不变), 左表中不存在的列用NaN填充"
   ],
   "id": "9d885b5f7a8684bf",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  key1  data1 key2  data2\n",
      "0    b      1    b      7\n",
      "1    b      5    b      7\n",
      "2    a      0    a      9\n",
      "3    a      2    a      9\n",
      "4    a      6    a      9\n",
      "5    b      2    b      7\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "  key1  data1 key2  data2\n",
       "0    a    0.0    a    9.0\n",
       "1    a    2.0    a    9.0\n",
       "2    a    6.0    a    9.0\n",
       "3    b    1.0    b    7.0\n",
       "4    b    5.0    b    7.0\n",
       "5    b    2.0    b    7.0\n",
       "6    c    6.0  NaN    NaN\n",
       "7  NaN    NaN    d    5.0"
      ],
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>key1</th>\n",
       "      <th>data1</th>\n",
       "      <th>key2</th>\n",
       "      <th>data2</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>a</td>\n",
       "      <td>0.0</td>\n",
       "      <td>a</td>\n",
       "      <td>9.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>a</td>\n",
       "      <td>2.0</td>\n",
       "      <td>a</td>\n",
       "      <td>9.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>a</td>\n",
       "      <td>6.0</td>\n",
       "      <td>a</td>\n",
       "      <td>9.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>b</td>\n",
       "      <td>1.0</td>\n",
       "      <td>b</td>\n",
       "      <td>7.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>b</td>\n",
       "      <td>5.0</td>\n",
       "      <td>b</td>\n",
       "      <td>7.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>b</td>\n",
       "      <td>2.0</td>\n",
       "      <td>b</td>\n",
       "      <td>7.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>c</td>\n",
       "      <td>6.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>d</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-14T05:44:14.650510Z",
     "start_time": "2025-01-14T05:44:14.642518Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 处理重复列名\n",
    "df_obj1 = pd.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],\n",
    "                        'data' : np.random.randint(0,10,7)})\n",
    "df_obj2 = pd.DataFrame({'key': ['a', 'b', 'd'],\n",
    "                        'data' : np.random.randint(0,10,3)})\n",
    "#给相同的数据列添加后缀\n",
    "print(pd.merge(df_obj1, df_obj2, on='key', suffixes=('_left', '_right'))) #suffixes参数可以给相同列名添加后缀"
   ],
   "id": "9ed8a93b3e47637b",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  key  data_left  data_right\n",
      "0   b          4           0\n",
      "1   b          7           0\n",
      "2   a          2           3\n",
      "3   a          5           3\n",
      "4   a          4           3\n",
      "5   b          0           0\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-14T06:02:52.243620Z",
     "start_time": "2025-01-14T06:02:52.232101Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 按索引连接\n",
    "df_obj1 = pd.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],\n",
    "                        'data1' : np.random.randint(0,10,7)})\n",
    "df_obj2 = pd.DataFrame({'data2' : np.random.randint(0,10,3)}, index=['a', 'b', 'd'])\n",
    "print(df_obj1)\n",
    "print(df_obj2)\n",
    "\n",
    "print(pd.merge(df_obj1, df_obj2, left_on='key', right_index=True)) # 按索引连接, 即用左表的key来连接右表的索引\n",
    "\n",
    "pd.merge(df_obj2,df_obj1, left_index=True, right_on='key') # 按索引连接, 即用右表的key来连接左表的索引"
   ],
   "id": "3eb7f1f5e4c66efe",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  key  data1\n",
      "0   b      2\n",
      "1   b      4\n",
      "2   a      1\n",
      "3   c      5\n",
      "4   a      9\n",
      "5   a      5\n",
      "6   b      5\n",
      "   data2\n",
      "a      6\n",
      "b      5\n",
      "d      1\n",
      "  key  data1  data2\n",
      "0   b      2      5\n",
      "1   b      4      5\n",
      "2   a      1      6\n",
      "4   a      9      6\n",
      "5   a      5      6\n",
      "6   b      5      5\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "   data2 key  data1\n",
       "2      6   a      1\n",
       "4      6   a      9\n",
       "5      6   a      5\n",
       "0      5   b      2\n",
       "1      5   b      4\n",
       "6      5   b      5"
      ],
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>data2</th>\n",
       "      <th>key</th>\n",
       "      <th>data1</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>6</td>\n",
       "      <td>a</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>6</td>\n",
       "      <td>a</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>6</td>\n",
       "      <td>a</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>5</td>\n",
       "      <td>b</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>5</td>\n",
       "      <td>b</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>5</td>\n",
       "      <td>b</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 11
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
